﻿using System;
using System.Net;
using System.Collections;

namespace Data_Storages
{
    public class DSNetServer : IDataStorage
    {
        private NetServer netServer = null;
        private byte[] message = null;
        public event EventHandler<NetServerMessageEventArgs> MessageEvent;
        private IDataStorage ds = null;

        public byte[] Message
        {
            get { return message; }
        }

        public IDataStorage DataStorage
        {
            get { return ds; }
        }

        public DSNetServer(string host, int port, IDataStorage ds)
        {
            IPAddress ip = null;
            netServer = null;
            message = null;
            this.ds = ds;
            if (IPAddress.TryParse(host, out ip))
            {
                netServer.MessageEvent += new EventHandler<NetServerMessageEventArgs>(netServer_MessageEvent);
                netServer = new NetServer(ip, port);
                netServer.Start(10);
                
            }
            else
            {
                throw new Exception("Error while initializing DSNetServer");
            }
        }

        void netServer_MessageEvent(object sender, NetServerMessageEventArgs e)
        {
            message = e.Message;
            OnMessageEvent(new NetServerMessageEventArgs(e.Message));
            //throw new NotImplementedException();
        }

        protected virtual void OnMessageEvent(NetServerMessageEventArgs args)
        {
            EventHandler<NetServerMessageEventArgs> handler = MessageEvent;
            if (handler != null)
            {
                handler(this, args);
            }
        }

        public void Save(ArrayList data)
        {
            if (data != null)
            {
                ds.Save(data);
            }
            else
            {
                throw new Exception("Error: nothing to save");
            }
        }

        public ArrayList Load()
        {
            //message = (byte[])ds.Load();
            ArrayList al = new ArrayList();
            return al;
        }
    }
}
